<template>
  <el-card class="con-top">
    <el-tree
      ref="treeRef"
      :data="treeList"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
    />
    <div class="button">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button @click="empty">清空</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import {
  ApiGetRoleListMenu,
  ApiGetMenuTreeList,
  ApiAddRoleAllocMenu,
} from './api'
import { useRoute } from 'vue-router'
import { ref } from 'vue'
import { ElTree } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

const treeRef = ref<InstanceType<typeof ElTree>>()

const route = useRoute()
// 菜单列表
const treeList = ref<ITreeList[]>([])
// 已选中的数据
const currTreeList = ref<number[]>([])

const defaultProps = {
  children: 'children',
  label: 'title',
}

// 页面数据初始化
if (route.query.id) {
  Promise.all([
    ApiGetRoleListMenu(parseInt(route.query.id as string)),
    ApiGetMenuTreeList(),
  ])
    .then((resolve) => {
      treeList.value = resolve[1].data
      // 已勾选的数据
      resolve[0].data.forEach((item) => {
        currTreeList.value.push(item.id)
      })
      treeRef.value!.setCheckedKeys(currTreeList.value, false)
    })
    .catch(() => {})
}

// 保存按钮
const submit = () => {
  ElMessageBox.confirm('此操作将为用户添加菜单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      ApiAddRoleAllocMenu({
        roleId: parseInt(route.query.id as string),
        menuIds: treeRef.value!.getCheckedKeys(false) as number[],
      }).then((res) => {
        if (res.code === 200) {
          ApiGetRoleListMenu(parseInt(route.query.id as string))
          ElMessage.success('保存成功！')
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'success',
        message: '您已取消',
      })
    })
}

// 清空按钮
const empty = () => {
  treeRef.value!.setCheckedKeys([], false)
}
</script>

<style lang="less" scoped>
.button {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
